﻿using System;
using System.IO;
using System.Text;
using System.Linq;
using System.ComponentModel;
using System.Net.Sockets;
using System.Collections.Generic;
using psafth.AMB.Objects;

namespace psafth.AMB
{
    public class AMBListener : BackgroundWorker
    {
        /// <summary>
        /// The host to connect to
        /// </summary>
        public string IPAddress
        {
            get;
            set;
        }

        /// <summary>
        /// The port to connect on
        /// </summary>
        public int Port
        {
            get;
            set;
        }

        /// <summary>
        /// Constructs the object
        /// </summary>
        /// <param name="ipAddress">The host to connect to</param>
        /// <param name="port">The port to connect on</param>
        public AMBListener(string ipAddress, int port)
        {
            this.IPAddress = ipAddress;
            this.Port = port;
        }

        /// <summary>
        /// Stores the bytes read from the stream. If exception been thrown, this is saved in lastrecord.ba
        /// </summary>
        private byte[] _tmpArray;

        protected override void OnDoWork(DoWorkEventArgs e)
        {
            base.OnDoWork(e);

            try
            {
                TcpClient tcpSocket = new TcpClient(IPAddress, Port);

                NetworkStream stream = tcpSocket.GetStream();
                stream.ReadTimeout = 15000;

                while (tcpSocket.Connected && !CancellationPending)
                {
                    Byte[] data = new Byte[64];

                    if (stream.DataAvailable)
                    {
                        // Read the first batch of the TcpServer response bytes.
                        Int32 bytes = stream.Read(data, 0, data.Length);

                        // Remove unessessssaarrrtyy bytes.
                        _tmpArray = new byte[bytes];

                        for (int i = 0; i < bytes; i++)
                        {
                            _tmpArray[i] = data[i];
                        }
                        
                        ReceiverObject receivedObject = new ReceiverObject(_tmpArray);

                        if (receivedObject.Message.CRCValid)
                        {
                            this.ReportProgress(0, receivedObject);
                        }
                        else
                        {
                            // TODO: Implement resend action;

                            // tcpSocket.Client.Send();
                        }
                    }
                }

                if (CancellationPending)
                {
                    e.Cancel = true;
                }
            }
            catch (Exception)
            {
                try
                {
                    File.WriteAllBytes("lastrecord.ba", _tmpArray);
                }
                catch (Exception)
                {
                }
                //System.IO.File.AppendAllLines("ErrorLog.txt", BitConverter.ToString(_tmpArray));
                //MessageBox.Show(ex.ToString(), "Ett fel har inträffat", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        } 
    }
}
